<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.status"
          placeholder="状态"
          class="handle-select mr10"
        >
          <el-option key="1" label="成功" value="1"></el-option>
          <el-option key="0" label="失败" value="0"></el-option>
        </el-select>
        <common-item1
          :query="query"
          :streetList="streetList"
          :communityList="communityList"
          :villageList="villageList"
          @visibleChangeStreet="visibleChangeStreet"
          @changeStreet="changeStreet"
          @visibleChangeCommunity="visibleChangeCommunity"
          @changeCommunity="changeCommunity"
          @visibleChangeVillage="visibleChangeVillage"
          @changeVillage="changeVillage"
          :showInput="showInput"
          @search="handleSearch"
        />
        <el-button
          type="primary"
          class="handle-input mb10"
          @click="handleSearch"
          >查询</el-button
        >
        <el-button
          type="danger"
          class="handle-input mb10"
          @click="delAllSelection"
          v-if="hplPermissions.includes('village:householdpush:delete')"
          >删除</el-button
        >
        <el-button
          type="primary"
          class="handle-input mb10"
          @click="handleExport"
          v-if="hplPermissions.includes('village:householdpush:export')"
          >导出</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="streetName"
          label="街道名"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="communityName"
          label="社区名"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="villageName"
          label="小区名"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="buildingNo"
          label="搂栋号"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="unitNo"
          label="单元号"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="houseNumber"
          label="门牌号"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="rfid"
          label="芯片号码"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="message"
          label="结果描述"
        ></el-table-column>

        <el-table-column prop="createDate" label="推送时间"></el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.status.toString() === '1'
                  ? 'success'
                  : scope.row.status.toString() === '0'
                  ? 'danger'
                  : ''
              "
              >{{
                scope.row.status.toString() === "1"
                  ? "成功"
                  : scope.row.status.toString() === "0"
                  ? "失败"
                  : ""
              }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="hplPermissions.includes('village:householdpush:delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import NProgress from "nprogress";
import { mapGetters } from "vuex";
import { commonItem1 } from "../../common/commonItem1/common-item1.js";
// console.log(commonItem1);
export default {
  name: "householdpushlog",
  // mixins: [commonItem1], // 混入太慢了 导致报错
  data() {
    return {
      hplPermissions: [],
      query: {
        status: "",
        pageIndex: 1,
        pageSize: 20,
        streetId: "",
        communityId: "",
        villageId: "",

        streetName: "",
        communityName: "",
        villageName: "",

        buildingNum: "",
        unitNum: "",
        houseNum: "",
        villageName: "",
      },
      showInput: true,
      streetList: [],
      communityList: [],
      villageList: [],

      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      pageTotal: 0,
      idx: -1,
      id: -1,
      ids: [],
    };
  },
  created() {
    this.getData();
    this.hplPermissions = this.permissions;
  },
  components: {
    "common-item1": () => import("../../common/commonItem1/common-item1.vue"),
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/householdpush-log") {
        this.hplPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      this.hplPermissions = newVal;
    },
  },
  methods: {
    // handleKeyword(keyword) {
    //   console.log(keyword);
    //   this.query.villageName = keyword;
    // },
    ...commonItem1,
    // 获取 easy-mock 的模拟数据
    getData() {
      NProgress.start();
      this.$axios
        .get("/village/householdpush/page", {
          params: {
            page: this.query.pageIndex,
            limit: this.query.pageSize,
            villageId: this.query.villageId,
            buildingNo: this.query.buildingNum,
            unitNo: this.query.unitNum,
            houseNumber: this.query.houseNum,
            status: this.query.status,
            villageName:
              this.showInput == false ? "" : this.query.villageName.trim(),
          },
        })
        .then(({ data: res }) => {
          console.log(res);
          if (res.code !== 0) {
            NProgress.done();
            return this.$message.error(res.msg);
          }
          res.data.list.map((item, index) => {
            var pageIndex = this.query.pageIndex;
            item.index = index + 1 + (pageIndex - 1) * this.query.pageSize;
            item.createDate = this.dateFormat(item.createDate);
          });
          this.tableData = res.data.list;
          this.pageTotal = res.data.total || 0;
          NProgress.done();
        })
        .catch((err) => {});
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);

      if (
        this.query.villageName.trim() == "" &&
        this.query.villageId.trim() == ""
      ) {
        return this.$message.warning({
          message: "请先选择小区",
          duration: 1500,
        });
      }
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids = [];
      var ids = this.ids;
      ids[0] = row.id;
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.delete(ids);
        })
        .catch(() => {});
    },
    delete(ids) {
      this.$axios
        .delete("/village/householdpush", {
          data: ids,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");
          this.ids = [];
          this.getData();
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.ids = [];
      var ids = this.ids;
      val.forEach((item, index) => {
        ids.push(item.id);
      });
    },
    delAllSelection() {
      var ids = this.ids;
      ids = [...new Set(ids)];
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.delete(ids);
        })
        .catch(() => {});
    },
    // 导出
    handleExport() {
      if (
        !Boolean(this.query.streetId) &&
        this.query.villageName.trim() == ""
      ) {
        return this.$message.warning({
          message: "请选择查询的街道,社区,小区",
          duration: 1500,
        });
      }
      NProgress.start();
      this.$axios
        .get("/village/householdpush/export", {
          params: {
            status: this.query.status,
            villageId: this.query.villageId,
            buildingNo: this.query.buildingNum,
            unitNo: this.query.unitNum,
            houseNumber: this.query.houseNum,
            villageName:
              this.showInput == false ? "" : this.query.villageName.trim(),
          },
          responseType: "blob",
        })
        .then((res) => {
          console.log(res);
          if (res.data.type != "application/vnd.ms-excel") {
            NProgress.done();
            return this.$message.error({
              message: "导出失败",
              duration: 1500,
            });
          }

          // 导出excel表格
          const link = document.createElement("a");
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          let num = "";
          for (let i = 0; i < 10; i++) {
            num += Math.ceil(Math.random() * 10);
          }
          link.setAttribute("download", "用户_" + num + ".xls");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          NProgress.done();
        })
        .catch(() => {});
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.$set(this.query, "pageSize", val);
      this.getData();
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: auto;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
